import { createRouter, createWebHistory } from 'vue-router'
import generatedRoutes from 'virtual:generated-pages';

//剔除非index.vue的页面
const routesList = []
for (const i in generatedRoutes) {
    const item = generatedRoutes[i]
    if (item.indexPage) routesList.push(item)
}
// 一级tree结构
const tree = {}
for (const i in routesList) {
    const item = routesList[i]
    const split = item.path.split('/')
    if (!tree[split[1]]) tree[split[1]] = {}
    if (!tree[split[1]].children) tree[split[1]].children = []
    if (split.length == 2) {
        tree[split[1]] = {
            ...item,
            children: tree[split[1]].children
        }
    } else {
        tree[split[1]].children.push(item)
    }
}
// 默认一级去除主文件夹名 如路由:/frame/welcome 改为 /welcome
const main = 'frame'
const mainChild = []
if (tree[main].children) {
    for (const i in tree[main].children) {
        const item = tree[main].children[i]
        item.path = item.path.replace('/' + main, '');
        mainChild.push(item)
    }
}
delete tree[main];//防止路由重复这里直接把原路由删掉
// 拼凑路由
const routes = [
    ...Object.values(tree),
    {
        path: '/',
        component: () => import('@/views/frame/index.vue'),
        children: [
            {
                path: '/',
                component: () => import('@/views/frame/welcome/index.vue')
            }, ...mainChild
        ]
    },
    {
        path: '/:pathMatch(.*)*',
        component: () => import('@/views/404/index.vue')
    }
];
//create
const router = createRouter({
    history: createWebHistory(import.meta.env.VITE_BASE),
    routes
})

// 设置路由守卫(登陆判断)
const noLogin = ['/404', '/login']
router.beforeEach((to, from, next) => {
    if (!noLogin.includes(to.path)) {//需要登陆
        const loginInfo = func.jsonStorage(config.storage.loginInfo)
        const token = localStorage.getItem(config.storage.loginToken) || ''
        if (token.length != 32 || !loginInfo.id) {
            let toUrl = '/login?back=' + encodeURIComponent(to.fullPath)
            if (to.fullPath == '/') toUrl = '/login'
            next(toUrl)
        } else {
            next()//有token但是这里不判断,留给接口去判断
        }
    } else {//不需要登陆
        next()
    }
});

export default router